<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
    <link rel="stylesheet" href="/assets/bootstrap/dist/css/bootstrap.min.css" />
    <style type="text/css">
      .container {
        padding-top: 60px;
      }
      .padding {
        padding: 5px 0 20px 0;
      }
    </style>
  </head>
  <body>
    <div class="container">
      <div class="form-group">
        <label>请选择文件</label>
        <!-- a1 -->
        <input type="file" name="up_file" id="file" />
        <!-- a14 -->
        <div class="progress">
          <div class="progress-bar" style="width: 0%" id="bar">0%</div>
        </div>
        <div class="padding" id="box">
          <!-- <img src="" class="img-rounded img-responsive"> -->
        </div>
      </div>
    </div>
    <script>
      // a2
      let file = document.getElementById('file')
      // a18
      let bar = document.getElementById('bar')
      let box = document.getElementById('box')
      // a3
      file.onchange = function () {
        // a4 创建空的formData表单对象
        let formData = new FormData()
        // a5 将用户选择的文件追加到formData表单对象中
        // formData.append('attrName', this.files[0])
        formData.append('up_file', this.files[0])
        console.log('this-file', this)
        console.log('this.files', this.files)

        // a6 创建ajax对象
        let xhr = new XMLHttpRequest()
        // a7 配置请求方式，地址；
        xhr.open('post', '/upload')
        // a15  a16
        xhr.upload.onprogress = function (ev) {
          console.log(ev)
          // a17
          let res = (ev.loaded / ev.total) * 100 + '%'
          // 19
          bar.style.width = res
          bar.innerHTML = res
        }
        // a8
        console.log('formData a8', formData)
        xhr.send(formData)
        // a9 监听服务器端响应给客户端的数据
        xhr.onload = function () {
          // 如果服务器端返回的http状态码为200
          // 说明请求是成功的
          if (xhr.status == 200) {
            // a22
            console.log(JSON.parse(xhr.responseText))
            let res = JSON.parse(xhr.responseText)
            // a23
            let img = document.createElement('img')
            img.src = res.path
            img.onload = function () {
              box.appendChild(img)
            }
          }
        }
      }
    </script>
  </body>
</html>
